package com.android.agenda;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.widget.Toast;

import com.android.data.DatabaseHelper;
import com.android.entities.AgendaEntry;
import com.android.entities.Group;
import com.android.entities.HistoryEntry;

public class ScheduleHelper {
	
	private static final String TABLE_NAME = "schedule";	 
	private Context context;
	private SQLiteDatabase db;
	private DatabaseHelper openHelper;
	private SQLiteStatement insertStmt;
	private static final String INSERT = "insert into " + TABLE_NAME + "(_id, name, " +
			"category, address, _date, startTime, endTime, description) values (?, ?, ?, ?, ?, ?, ?, ?)";
	
	public ScheduleHelper(Context context) {
		this.context = context;
		this.openHelper = new DatabaseHelper(this.context);
		this.db = openHelper.getWritableDatabase();
		this.insertStmt = this.db.compileStatement(INSERT);
	}
	 
	public void close() {
		this.openHelper.close();
	}
	
	public long insert(long id, String name, String category, String address, 
			String date, String startTime, String endTime, String description) {	
		String mEventName = (name != null && name.length() > 0) ? name : "-";
		String mEventCategory = (category != null && category.length() > 0) ? category : "-";
		String mAddress = (address != null && address.length() > 0) ? date  : "-";
		String mDate = (date != null && date.length() > 0) ? date  : "-";
		String mStartTime = (startTime != null && startTime.length() > 0) ? startTime : "-";
		String mEndTime = (endTime != null && endTime.length() > 0) ? endTime : "-";
		String mDescription = (description != null && description.length() > 0) ? description : "-";
		
		this.insertStmt.bindLong(1, id);
		this.insertStmt.bindString(2, mEventName);
		this.insertStmt.bindString(3, mEventCategory);
		this.insertStmt.bindString(4, mAddress);
		this.insertStmt.bindString(5, mDate);
		this.insertStmt.bindString(6, mStartTime);
		this.insertStmt.bindString(7, mEndTime);
		this.insertStmt.bindString(8, mDescription);
		
		return this.insertStmt.executeInsert();
	}
	 
	public void deleteAll() {
		this.db.delete(TABLE_NAME, "1", null);
	}

	public void deleteRows(String filter) {
		this.db.delete(TABLE_NAME, filter, null);
	}

	public ArrayList<AgendaEntry> selectAll() {
		ArrayList<AgendaEntry> list = new ArrayList<AgendaEntry>();
		
		Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "name", "category", "address", 
				"startTime", "endTime", "_date", "description"}, null, null, null, null, "_date");
		
		if (cursor.moveToFirst()) {
			do {				
				AgendaEntry entry = new AgendaEntry();
				entry.setId(cursor.getString(0));
				entry.setName(cursor.getString(1));
				entry.setCategory(cursor.getString(2));
				entry.setAddress(cursor.getString(3));
				entry.setStartTime(cursor.getString(4));
				entry.setEndTime(cursor.getString(5));
				entry.setDate(cursor.getString(6));
				entry.setDescription(cursor.getString(7));
				
				list.add(entry);
				
			} while (cursor.moveToNext());
		}
		
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		
		Collections.sort(list, new Comparator<Object>(){
			 
            public int compare(Object o1, Object o2) {
                AgendaEntry p1 = (AgendaEntry) o1;
                AgendaEntry p2 = (AgendaEntry) o2;
               return p1.getDate().compareTo(p2.getDate());
            }
 
        });
		
		return list;
	}
	
	public ArrayList<Group> selectAllGroups() {
		ArrayList<Group> listGroups = new ArrayList<Group>(); 
		ArrayList<AgendaEntry> list = selectAll();
		DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
		
		Date lastDate = null;
		Group g = new Group();
		
		for (AgendaEntry e: list) {
	
			if (lastDate == null || !lastDate.equals(e.getDate())) {
				lastDate = e.getDate();
				String dateStr = fmt.format(e.getDate());
				g = new Group(dateStr);
				
			} else {
				g = listGroups.remove(listGroups.size() - 1);
			}
		
			g.addChild(e);
			listGroups.add(g);
		}   	
			
		return listGroups;
	}

	public ArrayList<HistoryEntry> selectOldEvents() {
		ArrayList<HistoryEntry> list = new ArrayList<HistoryEntry>();
		String ids = "(";
		Date date = new java.util.Date(System.currentTimeMillis());
		DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
		int count = 0;
		
		//Get old events
		ArrayList<AgendaEntry> oldEvents = selectAll();
		for (AgendaEntry e: oldEvents) {
			
			if (e.getDate().before(date)) {
				HistoryEntry he = new HistoryEntry();
				he.setId(e.getId());
				he.setName(e.getName());
				he.setDate(fmt.format(e.getDate()));
				list.add(he);
				
				count += 1;
				ids += "\'" + e.getId() + "\', ";
			}
			
		}
		
		if (count == 0)
			return list;

		ids = ids.substring(0, ids.length()-2);
		ids += ")";
		//Delete events from schedule table
		deleteRows("_id IN " + ids);
		
		return list;
	}
	
	public AgendaEntry selectEvent(String eventId) {
		AgendaEntry entry = new AgendaEntry();
		String filter = "_id = \'" + eventId + "\'"; 
		
		Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "name", "category", "address", 
				"startTime", "endTime", "_date", "description"}, filter, null, null, null, "_date");
		
		if (cursor.moveToFirst()) {
			do {				
				entry.setId(cursor.getString(0));
				entry.setName(cursor.getString(1));
				entry.setCategory(cursor.getString(2));
				entry.setAddress(cursor.getString(3));
				entry.setStartTime(cursor.getString(4));
				entry.setEndTime(cursor.getString(5));
				entry.setDate(cursor.getString(6));
				entry.setDescription(cursor.getString(7));
								
			} while (cursor.moveToNext());
		}
		
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		
		return entry;
	}
	
	public void createAgendaEntry(long id, String name, String category, String address, 
			String date, String startTime, String endTime, String description) {
		try {
			insert(id, name, category, address, date, startTime, endTime, description);
			
		} catch (Exception e){
			e.printStackTrace();
			Toast.makeText(context, "error: " + e.getMessage(),
					Toast.LENGTH_LONG).show();
		}
	}
}
